package com.znxz.hzqiuxm.ziniublog.user.domain.services;

import com.znxz.hzqiuxm.ziniublog.user.domain.dao.UserRepository;
import com.znxz.hzqiuxm.ziniublog.user.domain.entity.UserDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * Copyright © 2018年 ziniuxiaozhu. All rights reserved.
 *
 * @Author 临江仙 hzqiuxm@163.com
 * 用户授权认证服务,需要实现SPringSecurity的UserDetailsService接口
 * @Date 2018/8/31 14:24
 */
@Slf4j
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    /**
     * 根据用户名或者手机号查询出用户信息
     * @param usernameOrCellName
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String usernameOrCellName) throws UsernameNotFoundException {

        log.info("JwtUserDetailsServiceImpl.loadUserByUsername is begin ... ... ");
        Optional<UserDO> user = userRepository.findByUserNameOrCellNum(usernameOrCellName, usernameOrCellName);

       return JwtUserFactory.create(
               user.orElseThrow(
                       ()->new UsernameNotFoundException(
                               String.format("No user found with username or cellnum '%s'.", usernameOrCellName))));
    }
}
